package com.hs.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fuyanru
 * @date 2024年05月02日 1:16
 */
@Data
@NoArgsConstructor
//@AllArgsConstructor
public class LoginUser implements UserDetails {
    // 用以封装用户信息
    private User user;
    //存储权限信息
    private List<String> permissions;


    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }
    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false)// 不序列化该字段
    private List<GrantedAuthority> authorities;
    // 用户的权限集
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
       //优化：第一次转换，后续调用直接返回
        if (authorities != null){
            return authorities;
        }
        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
        /*List<GrantedAuthority> authorityList = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority();
            authorityList.add(authority);
        }
        return authorityList;*/
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    // 用户的加密后的密码， 不加密会使用{noop}前缀
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    // 用户名
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    // 帐户未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 帐户未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 凭证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 用户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }


    public List<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }
}
